import os
from relic import Relic
from PIL import Image, ImageDraw, ImageFont
import re

current_directory = os.path.dirname(os.path.abspath(__file__))

point = Image.open("images/point.png")
static_relic_image = Image.open("images/background.png")
lock = Image.open("images/lock.png")
font_18 = ImageFont.truetype("../font.ttf", size=18)
font_20 = ImageFont.truetype("../font.ttf", size=20)
font_28 = ImageFont.truetype("../font.ttf", size=28)
font_35 = ImageFont.truetype("../font.ttf", size=35)


def generate_relic_img(relic: Relic) -> Image.Image:
    # 初始化创建空图片并粘贴底图片
    relic_image = Image.new(mode="RGB", size=(410, 700), color="#000000")
    relic_image.paste(static_relic_image)

    # 获取绘制对象
    draw = ImageDraw.Draw(relic_image)

    # 绘制圣遗物名称和类型和数值
    draw.text(font=font_28, xy=(24, 7), text=relic.name)
    draw.text(xy=(24, 57), text=relic.relic_type, font=font_18)

    draw.text(xy=(24, 125), text=relic.main_entry_type.replace("百分比",""), fill="#bdaea9", font=font_18)
    draw.text(xy=(24, 147)
              , text=re.findall(r'\d+\.\d+%|\d+%|\d+\.\d+|\d+', relic.main_entry_str)[0]
              , font=font_35)

    y_pointer = 256  # 用来指示文字y坐标的指示器
    # 绘制圣遗物等级
    draw.text(xy=(24 + int((-7.0 / 20.0) * relic.level + 10), y_pointer), text="+" + str(relic.level),
              font=font_20)
    y_pointer = 299
    # 绘制副词条列表
    for i in range(len(relic.secondary_lemma_str)):
        draw.text(xy=(44, y_pointer), text=relic.secondary_lemma_str[i], font=font_20, fill="#495366")

        y_pointer += 32
    draw.text(xy=(24, y_pointer), text=relic.coordinate_name, font=font_20, fill="#5cb256")

    y_pointer += 32
    # 绘制两件套和四件套文字
    draw.text(xy=(44, y_pointer), text=relic.两件套, font=font_20, fill="#707681")
    y_pointer += font_20.getbbox(text=relic.两件套)[3] + 10
    draw.text(xy=(44, y_pointer), text=relic.四件套, font=font_20, fill="#707681")
    for i in range(len(relic.secondary_lemma_type)):
        relic_image.paste(im=point, box=(32, 32 * i + 308))

    # 判断是否锁了，如果是的话就贴一个锁的图片
    if relic.locked:
        relic_image.paste(im=lock, box=(353, 249))

    # 粘贴圣遗物图片
    img = relic.img.crop(box=(0, 0, 0.98 * relic.img.width, 0.83 * relic.img.height))
    img = img.resize(size=(int(img.width * (162 / img.height)), 162))
    relic_image.paste(im=img, box=(221, 49))
    relic_image = relic_image.crop((0,0,410,460))
    # print(np.array(relic_image).shape)
    return relic_image
